package jndi.ldap.factory;

import jndi.ldap.LdapConnection;
import jndi.ldap.LdapEnv;

import java.util.*;

import javax.naming.Context;
import javax.naming.NamingException;

public class DefaultLdapConnectionManager implements LdapConnectionManager {


    private static final LdapConnectionManager CONNECTION_MANAGER = new DefaultLdapConnectionManager();

    public static LdapConnectionManager getInstance() {
        return CONNECTION_MANAGER;
    }

    private DefaultLdapConnectionManager() {
        super();
    }

    private Hashtable<String, String> getDefaultLdapEnv() {
        return LdapEnv.getDefaultLdapEnv();
    }

    private LdapConnection openConnection(Hashtable<String, String> env) {
        LdapConnection connection = null;

        try {
            connection = new LdapConnection(env, null);
            connection.setConnectionManager(this);
        } catch (NamingException e) {
            e.printStackTrace();
        }

        return connection;
    }

    public LdapConnection openConnection() {
        Hashtable<String, String> env = getDefaultLdapEnv();
        return openConnection(env);
    }


    public LdapConnection openConnection(String url) {
        Hashtable<String, String> env = getDefaultLdapEnv();
        env.put(Context.PROVIDER_URL, url);
        return openConnection(env);
    }

    public LdapConnection openConnection(String username, String passwd) {
        Hashtable<String, String> env = getDefaultLdapEnv();
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, passwd);
        return openConnection(env);
    }

    public LdapConnection openConnection(String url, String username, String passwd) {
        Hashtable<String, String> env = getDefaultLdapEnv();
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, passwd);
        return openConnection(env);
    }

    public void closeConnection(LdapConnection connection) {
        try {
            connection.close();
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }
    }
}
